package org.zoomdev.zoom.web.rendering.impl;

import jakarta.servlet.http.HttpServletResponse;
import org.zoomdev.zoom.common.exceptions.CodeException;
import org.zoomdev.zoom.common.utils.MapUtils;
import org.zoomdev.zoom.web.action.ActionContext;
import org.zoomdev.zoom.web.exception.StatusException;
import org.zoomdev.zoom.web.utils.ResponseUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public final class JsonRendering extends BaseRendering {


    @Override
    protected void processThrowable(ActionContext context, Throwable exception) {
        HttpServletResponse response = context.getResponse();
        if (exception instanceof StatusException) {
            StatusException statusException = (StatusException) exception;
            response.setStatus(statusException.getStatus());
            ResponseUtils.writeJson(response, MapUtils.asMap("code", statusException.getCode(), "error", statusException.getMessage()), false);
            return;
        }

        /**
         * 针对业务错误(CodeException)进行输出
         */
        if (exception instanceof CodeException) {
            CodeException statusException = (CodeException) exception;
            response.setStatus(StatusException.ApiError.STATUS);
            ResponseUtils.writeJson(response, MapUtils.asMap("code", statusException.getCode(), "error", statusException.getMessage()), false);
            return;
        }

        if (exception instanceof TimeoutException || exception instanceof IOException) {
            response.setStatus(StatusException.ApiError.STATUS);
            ResponseUtils.writeJson(response, MapUtils.asMap("code", "io", "error", exception.getMessage()), false);
            return;
        }


        response.setStatus(500);
        ResponseUtils.writeJson(response, MapUtils.asMap("code", exception.getClass().getName(),
                "error", exception.getMessage()), false);
    }

    @Override
    protected void processNormal(ActionContext context) {
        ResponseUtils.writeJson(context.getResponse(), context.getResult(), false);
    }
}
